import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { 
  Button, 
  Card, 
  Tag, 
  Space, 
  message, 
  Table, 
  Popconfirm,
  Modal,
  Input,
  Typography,
  Tabs
} from 'antd';
import { 
  EditOutlined, 
  DeleteOutlined, 
  PlusOutlined, 
  MinusOutlined,
  BookOutlined,
  TeamOutlined,
  GlobalOutlined,
  UserOutlined,
  CalendarOutlined,
  OrderedListOutlined,
  CodeOutlined,
  FileTextOutlined,
  DragOutlined,
  TrophyOutlined
} from '@ant-design/icons';
import ReactMarkdown from '@/components/MDEditor';
import { ProblemSet, ProblemSetProblem } from '@/types/problemSet';
import { problemSetService } from '@/services/problemSetService';
import DraggableList from '@/components/DraggableList';
import Leaderboard from './components/Leaderboard';
import styles from './ProblemSetDetail.module.css';
import '@/styles/markdown.css';

const { Title, Paragraph, Text } = Typography;
const { TabPane } = Tabs;

interface ProblemSetDetailProps {
  isAdmin?: boolean;
  basePath?: string;
}

const ProblemSetDetail: React.FC<ProblemSetDetailProps> = ({ 
  isAdmin = false,
  basePath = '/problem' 
}) => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [problemSet, setProblemSet] = useState<ProblemSet | null>(null);
  const [problems, setProblems] = useState<ProblemSetProblem[]>([]);
  const [problemsLoading, setProblemsLoading] = useState(false);
  
  // 添加题目相关状态
  const [addProblemModalVisible, setAddProblemModalVisible] = useState(false);
  const [newProblemId, setNewProblemId] = useState('');

  const fetchProblemSet = async () => {
    if (!id) return;
    
    try {
      setLoading(true);
      const response = await problemSetService.getProblemSet(parseInt(id));
      setProblemSet(response.data.data);
    } catch (error) {
      message.error('获取题单详情失败');
      // 如果basePath是/practice/problem-set，返回/practice；否则返回/problem/problem-sets
      const backPath = basePath === '/practice/problem-set' ? '/practice' : `${basePath}/problem-sets`;
      navigate(backPath);
    } finally {
      setLoading(false);
    }
  };

  const fetchProblems = async () => {
    if (!id) return;
    
    try {
      setProblemsLoading(true);
      const response = await problemSetService.getProblemSetProblems(parseInt(id));
      const data = response.data.data;
      setProblems(data);
    } catch (error) {
      message.error('获取题目列表失败');
    } finally {
      setProblemsLoading(false);
    }
  };

  useEffect(() => {
    fetchProblemSet();
    fetchProblems();
  }, [id]);

  const handleDelete = async () => {
    if (!id) return;
    
    try {
      await problemSetService.deleteProblemSet(parseInt(id));
      message.success('删除成功');
      // 如果basePath是/practice/problem-set，返回/practice；否则返回/problem/problem-sets
      const backPath = basePath === '/practice/problem-set' ? '/practice' : `${basePath}/problem-sets`;
      navigate(backPath);
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleAddProblem = async () => {
    if (!id || !newProblemId.trim()) {
      message.error('请输入题目ID');
      return;
    }

    try {
      await problemSetService.addProblemToSet(parseInt(id), {
        problem_id: newProblemId.trim()
      });
      message.success('添加题目成功');
      setAddProblemModalVisible(false);
      setNewProblemId('');
      fetchProblems(); // 刷新题目列表
    } catch (error: any) {
      if (error.response?.data?.message) {
        message.error(error.response.data.message);
      } else {
        message.error('添加题目失败');
      }
    }
  };

  const handleRemoveProblem = async (problemId: string) => {
    if (!id) return;

    try {
      await problemSetService.removeProblemFromSet(parseInt(id), {
        problem_id: problemId
      });
      message.success('移除题目成功');
      fetchProblems(); // 刷新题目列表
    } catch (error: any) {
      if (error.response?.data?.message) {
        message.error(error.response.data.message);
      } else {
        message.error('移除题目失败');
      }
    }
  };

  // 处理拖拽排序结束
  const handleDragEnd = async (newProblems: ProblemSetProblem[]) => {
    if (!id) return;

    try {
      // 更新本地状态
      setProblems(newProblems);
      
      // 批量更新题目顺序到后端
      const updatePromises = newProblems.map((problem, index) => {
        return problemSetService.updateProblemOrder(parseInt(id), {
          problem_id: problem.problem._id,
          order: index + 1
        });
      });

      await Promise.all(updatePromises);
      message.success('题目顺序更新成功');
    } catch (error) {
      message.error('更新题目顺序失败');
      // 如果更新失败，重新获取数据
      fetchProblems();
    }
  };

  const renderProblemItem = (problem: ProblemSetProblem, index: number) => {
    return (
      <div className={styles.problemRow}>
        <div className={styles.orderCell}>
          <Tag 
            color={problem.user_status === true ? "success" : problem.user_status === false ? "error" : "blue"}
            style={problem.user_status === true ? { 
              backgroundColor: '#389e0d', 
              color: 'white',
              border: 'none'
            } : problem.user_status === false ? {
              backgroundColor: '#cf1322',
              color: 'white',
              border: 'none'
            } : {
              backgroundColor: 'white',
              color: '#1890ff',
              border: '1px solid #1890ff'
            }}
          >
            {problem.order}
          </Tag>
        </div>
        <div className={styles.problemIdCell}>
          {problem.problem._id}
        </div>
        <div className={styles.titleCell}>
          <a 
            onClick={() => navigate(`/problem/${problem.problem.id}/submit?origin=problemset&problemSetId=${id}`)}
            style={{ color: 'var(--primary-color)', cursor: 'pointer' }}
          >
            {problem.problem.title}
          </a>
        </div>
        <div className={styles.actionCell}>
          <Space size="small">
            <Button 
              type="link" 
              size="small"
              icon={<CodeOutlined />} 
              onClick={() => navigate(`/problem/${problem.problem.id}/submit?origin=problemset&problemSetId=${id}`)}
            >
              答题
            </Button>
            
            {isAdmin && (
              <>
                <Button 
                  type="link" 
                  size="small"
                  icon={<EditOutlined />} 
                  onClick={() => {
                    const currentUrl = window.location.pathname + window.location.search;
                    navigate(`/admin/problem/edit/${problem.problem.id}?returnUrl=${encodeURIComponent(currentUrl)}`);
                  }}
                >
                  修改
                </Button>
                <Popconfirm
                  title="确定要从题单中移除这道题目吗？"
                  onConfirm={() => handleRemoveProblem(problem.problem._id)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button 
                    type="link" 
                    size="small"
                    danger 
                    icon={<MinusOutlined />}
                  >
                    移除
                  </Button>
                </Popconfirm>
              </>
            )}
          </Space>
        </div>
      </div>
    );
  };

  const renderDragHandle = (problem: ProblemSetProblem, index: number) => {
    return (
      <div className={styles.dragCell}>
        <DragOutlined className={styles.dragIcon} />
      </div>
    );
  };



  const problemListHeader = (
    <div className={styles.problemRowHeader}>
      <div className={styles.dragHeaderCell}>排序</div>
      <div className={styles.orderCell}>序号</div>
      <div className={styles.problemIdCell}>题目ID</div>
      <div className={styles.titleCell}>题目标题</div>
      <div className={styles.actionCell}>操作</div>
    </div>
  );

  if (loading) {
    return <div>加载中...</div>;
  }

  if (!problemSet) {
    return <div>题单不存在</div>;
  }

  return (
    <div>
      {/* 题单标题卡片 */}
      <Card style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <Title level={2} style={{ margin: 0, marginBottom: 8 }}>
              <BookOutlined style={{ marginRight: 8 }} />
              {problemSet.title}
            </Title>
            <div style={{ color: 'var(--text-secondary)', fontSize: '14px' }}>
              <Space size="large">
                <span>
                  <OrderedListOutlined /> {problemSet.problem_count} 题
                </span>
                <span>
                  {problemSet.visibility === 'public' ? <GlobalOutlined /> : <TeamOutlined />}
                  {problemSet.visibility === 'public' ? '公开' : '团队'}
                </span>
                <span>
                  <UserOutlined /> {problemSet.creator_name}
                </span>
                <span>
                  <CalendarOutlined /> {new Date(problemSet.created_time).toLocaleDateString()}
                </span>
                {problemSet.team_name && (
                  <span>
                    <TeamOutlined /> {problemSet.team_name}
                  </span>
                )}
              </Space>
            </div>
            <Paragraph style={{ marginTop: 12, marginBottom: 0, color: 'var(--text-secondary)' }}>
              {problemSet.description}
            </Paragraph>
          </div>
          {isAdmin && (
            <Space>
              <Button
                type="primary"
                icon={<EditOutlined />}
                onClick={() => navigate(`${basePath}/problem-set/edit/${id}`)}
              >
                编辑题单
              </Button>
              <Popconfirm
                title="确定要删除这个题单吗？"
                onConfirm={handleDelete}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  danger
                  icon={<DeleteOutlined />}
                >
                  删除题单
                </Button>
              </Popconfirm>
            </Space>
          )}
        </div>
      </Card>

      {/* 主要内容区域 - Tab布局 */}
      <Card style={{ marginTop: 16 }}>
        <Tabs
          defaultActiveKey="content"
          items={[
            {
              key: 'content',
              label: (
                <Space>
                  <FileTextOutlined />
                  知识清单
                </Space>
              ),
              children: (
                <div style={{ padding: '16px 0' }}>
                  <div style={{ 
                    backgroundColor: '#fafafa', 
                    padding: '24px', 
                    borderRadius: '8px',
                    border: '1px solid #f0f0f0'
                  }}>
                    <div className="markdown-content">
                      <ReactMarkdown
                        value={problemSet.content}
                        readOnly={true}
                        preview="preview"
                      />
                    </div>
                  </div>
                </div>
              ),
            },
            {
              key: 'problems',
              label: (
                <Space>
                  <OrderedListOutlined />
                  题目列表 ({problems.length})
                </Space>
              ),
              children: (
                <div style={{ padding: '16px 0' }}>
                  <div style={{ marginBottom: 16 }}>
                    {isAdmin && (
                      <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={() => setAddProblemModalVisible(true)}
                      >
                        添加题目
                      </Button>
                    )}
                  </div>
                  {isAdmin ? (
                    <DraggableList
                      dataSource={problems}
                      rowKey="id"
                      onDragEnd={handleDragEnd}
                      dragDisabled={false}
                      renderItem={renderProblemItem}
                      renderDragHandle={renderDragHandle}
                      header={problemListHeader}
                    />
                  ) : (
                    <div style={{ border: '1px solid #f0f0f0', borderRadius: '6px' }}>
                      {problemListHeader}
                      {problems.map((problem, index) => renderProblemItem(problem, index))}
                    </div>
                  )}
                </div>
              ),
            },
            {
              key: 'leaderboard',
              label: (
                <Space>
                  <TrophyOutlined />
                  排行榜
                </Space>
              ),
              children: (
                <div style={{ padding: '16px 0' }}>
                  <Leaderboard 
                    problemSetId={parseInt(id || '0')} 
                    isTeamProblemSet={problemSet?.visibility === 'team'}
                  />
                </div>
              ),
            },
          ]}
        />
      </Card>

      {/* 添加题目弹窗 */}
      <Modal
        title="添加题目到题单"
        open={addProblemModalVisible}
        onOk={handleAddProblem}
        onCancel={() => {
          setAddProblemModalVisible(false);
          setNewProblemId('');
        }}
        okText="添加"
        cancelText="取消"
      >
        <div style={{ marginBottom: 16 }}>
          <Text>请输入要添加的题目ID：</Text>
        </div>
        <Input
          placeholder="例如：1001"
          value={newProblemId}
          onChange={(e) => setNewProblemId(e.target.value)}
          onPressEnter={handleAddProblem}
        />
      </Modal>
    </div>
  );
};

export default ProblemSetDetail; 